package com.ijiuchuang.jc_localization.view.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ijiuchuang.jc_localization.R;
import com.ijiuchuang.jc_localization.bean.bmob.Product;
import com.ijiuchuang.jc_localization.bean.bmob.Result;
import com.ijiuchuang.jc_localization.network.ApiModel;
import com.ijiuchuang.jc_localization.tools.utils.Log;
import com.ijiuchuang.jc_localization.view.adapter.ProductListRecyclerAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProductFragment extends Fragment {


    @BindView(R.id.product_recycler)
    RecyclerView mRecyclerView;

    private ProductListRecyclerAdapter mRecyclerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_product, container, false);
        ButterKnife.bind(this, view);

        ApiModel.bmobGetApi()
                .getProducts()
                .map(new Func1<Result<Product>, List<Product>>() {
                    @Override
                    public List<Product> call(Result<Product> productResult) {
                        return productResult.results;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<Product>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("onError: " + e.toString());
                    }

                    @Override
                    public void onNext(List<Product> products) {
                        mRecyclerAdapter = new ProductListRecyclerAdapter(getActivity(), R.layout.recycler_item_product_list, products);
                        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
                        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                        mRecyclerView.setAdapter(mRecyclerAdapter);
                    }
                });

        return view;
    }

}
